package com.test;

import com.demo.dao.IUserDao;
import com.demo.dao.impl.UserDao;
import com.demo.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MyBatisTest3 {
    private static SqlSession sqlSession;
    @BeforeAll
    public static void init() throws IOException {
        InputStream in =  Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        sqlSession = sqlSessionFactory.openSession(true);
    }
    @Test
    public void testGetById(){
        // 拿到了MyBatis基于IUserDao接口动态产生的一个类对象
        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        User user = mapper.getById(1);
        System.out.println(user);
    }
    @Test
    public void testGetAll(){
        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        List<User> list = mapper.getAll();
        /*
        for (User user : list) {
            System.out.println(user);
        }

        list.forEach(item->{
            System.out.println(item);
        });
         */
        list.forEach(System.out::println);
    }
    @Test
    public void testRemoveUser(){
        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        Integer x = mapper.removeUser(5);
        System.out.println(x);
    }
    @Test
    public void testInsertUser(){
        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        User user = new User();
        user.setUserName("张三");
        user.setPassword("123456");
        user.setName("张三");
        user.setAge(18);
        user.setSex(1);
        user.setBirthday(new Date());
        user.setCreated(new Date());
        user.setUpdated(new Date());
        Integer x = mapper.insertUser(user);
        System.out.println(x);
    }
    @Test
    public void testChangeUser(){
        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        User user = new User();
        user.setId(14L);
        user.setUserName("王五");
        user.setPassword("4444");
        user.setName("五弟");
        user.setAge(12);
        user.setSex(0);
        user.setBirthday(new Date());
        user.setCreated(new Date());
        user.setUpdated(new Date());
        Integer x = mapper.changeUser(user);
        System.out.println(x);
    }
}
